/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2016-05-08 16:31:55
 * Last Modified: 2016-08-26 19:45:07
 * File Name: quiz/mediaid.go
 * Description:
 */
package filmvideo

import (
	"doubimeizhi.com/datatable"
	"doubimeizhi.com/seqno"

	"advertoper/db"

	log "github.com/cihub/seelog"
)

var (
	mediaidGenerator *seqno.SeqNoService
)

func createMediaIdGenerator() bool {
	if mediaidGenerator != nil {
		return true
	}
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("filmvideo")
	dtq.PushField(&datatable.FiledItem{Alias: "media_id", Field: "max(media_id)"})
	sql, values := dtq.GenerateSQL()
	mysqlHelper := db.GetMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Warnf("sql err: %s, sql: %s, values: %v", err.Error(), sql, values)
		return false
	}
	var id int64
	if len(results) > 0 {
		id = mysqlHelper.GetColInt64(results[0], "media_id")
	}
	mediaidGenerator = seqno.NewSeqNoService(id)
	return true
}

func ApplyNewMediaId() (bool, int64) {
	if mediaidGenerator == nil {
		if ret := createMediaIdGenerator(); !ret {
			return false, 0
		}
	}
	return true, mediaidGenerator.GetNextSeqNo()
}
